import { fetchAppleItem, editPerson, addDtl, deleteDtl } from "../../api/list";
import { uploadFile } from "../../api/user";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    personId: "",
    name: "",
    phoneNumber: "",
    address: "",
    fileList: [],
    pictures: [],
    pingJia: "",
    rukus: [],
    totalQty: 0,
    imgList: [],
    showDetail: false,
    guiGe: "",
    qty: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      personId: options.personId,
    });
    this.getPersonDetail();
  },

  getPersonDetail() {
    wx.showLoading({
      title: "加载中...",
      mask: true,
    });
    let params = {
      personId: this.data.personId,
    };
    fetchAppleItem(params).then((res) => {
      if (res) {
        let _imgs = res.pictures.map((item) => {
          return {
            url: item.pictureUrl,
          };
        });
        this.setData({
          name: res.name,
          phoneNumber: res.phoneNumber,
          address: res.address,
          pingJia: res.pingJia,
          rukus: res.rukus,
          pictures: res.pictures,
          fileList: _imgs,
          totalQty: res.totalQty,
        });
        setTimeout(() => {
          wx.hideLoading();
        }, 1000);
      }
    });
  },
  openDtlDialog() {
    this.setData({
      showDetail: true,
    });
  },
  // 表单保存
  save() {
    wx.showLoading({
      title: "正在提交...",
      mask: true,
    });
    if (!this.data.name) {
      wx.showToast({
        title: "请输入果农姓名",
        icon: "error",
      });
      return;
    }
    let picList = [];
    for (let i = 0, iLen = this.data.fileList.length; i < iLen; i++) {
      picList.push({
        pictureUrl: this.data.fileList[i].url,
      });
    }

    let params = {
      personId: this.data.personId,
      name: this.data.name,
      phoneNumber: this.data.phoneNumber,
      address: this.data.address,
      pingJia: this.data.pingJia,
      rukus: this.data.rukus,
      pictures: picList,
    };
    editPerson(null, params)
      .then((res) => {
        this.setData({
          personId: res.data,
        });
        wx.hideLoading();
        wx.navigateBack();
      })
      .catch((err) => {
        wx.showToast({
          title: err,
          icon: "error",
        });
      });
  },
  saveDtl() {
    if (this.data.guiGe && this.data.qty) {
      let params = {
        personId: parseInt(this.data.personId),
        guiGe: this.data.guiGe,
        qty: parseInt(this.data.qty),
      };
      addDtl(null, params)
        .then((res) => {
          if (res.code === 200) {
            this.setData({
              showDetail: false,
              guiGe: "",
              qty: 0,
            });
            this.getPersonDetail();
          }
        })
        .catch((err) => {
          wx.showToast({
            title: "保存错误：" + err.toString(),
            icon: "error",
          });
        });
    } else {
      wx.showToast({
        title: "请输入规格和数量",
        icon: "error",
        zIndex: 999,
        mask: true,
      });
      return;
    }
  },
  deleteDtl(e) {
    wx.showModal({
      title: "警告",
      content: "您确认要删除数据吗?",
      complete: (res) => {
        if (res.cancel) {
        }

        if (res.confirm) {
          let _params = {
            rukuId: e.currentTarget.dataset.id,
          };
          deleteDtl(null, _params)
            .then((res) => {
              if (res.code === 200) {
                this.getPersonDetail();
              }
            })
            .catch((err) => {
              wx.showToast({
                title: "删除数据异常" + err.toString(),
              });
            });
        }
      },
    });
  },
  setUserName(e) {
    this.setData({
      name: e.detail,
    });
  },
  setPhoneNumber(e) {
    this.setData({
      phoneNumber: e.detail,
    });
  },
  setAddress(e) {
    this.setData({
      address: e.detail,
    });
  },
  setComments(e) {
    this.setData({
      pingJia: e.detail,
    });
  },
  setGuiGe(e) {
    this.setData({
      guiGe: e.detail,
    });
  },
  setQty(e) {
    this.setData({
      qty: e.detail,
    });
  },
  onClosePop() {
    this.setData({
      showDetail: false,
    });
  },
  uploadFile(uploadFile) {
    let token = wx.getStorageSync("token");
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        //url: "https://crm.etransfar.com/xapi/api/upload", //config.uploadUrl, // 上传的服务器接口地址
        url: "https://crm.etransfar.com/xfx/api/File/upload",
        header: {
          Authorization: `Bearer ${token}`,
        },
        filePath: uploadFile,
        name: "file", //上传的所需字段，后端提供
        success: (res) => {
          console.log("resdata=", res);
          // 上传完成操作

          const url = res.data;
          resolve({
            url: url,
          });
        },
        fail: (err) => {
          //上传失败：修改pedding为reject
          reject(err);
        },
      });
    });
  },

  afterRead(event) {
    wx.showLoading({
      title: "上传中...",
    });
    const { file } = event.detail; //获取所需要上传的文件列表
    let uploadPromiseTask = []; //定义上传的promise任务栈

    for (let i = 0; i < file.length; i++) {
      uploadPromiseTask.push(uploadFile(file[i].tempFilePath));

      //uploadPromiseTask.push(this.uploadFile(file[i].tempFilePath)); //push进每一张所需要的上传的图片promise栈
    }
    Promise.all(uploadPromiseTask)
      .then((res) => {
        //全部上传完毕
        this.setData({
          fileList: this.data.fileList.concat(res),
        });
        console.log("上传", this.data.fileList);
        wx.hideLoading();
      })
      .catch((error) => {
        //存在有上传失败的文件
        wx.hideLoading();
        wx.showToast({
          title: "上传失败！",
          icon: "none",
        });
      });
  },

  deleteImg(event) {
    const delIndex = event.detail.index;
    const { fileList } = this.data;
    fileList.splice(delIndex, 1);
    this.setData({
      fileList,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
